package com.tgz.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @Description:编写一个类交由spring管理并继承KeyExpirationEventMessageListener，一个项目中可有多个监听器实例
 * @author HeShengjin 2356899074@qq.com
 * @date 2023/1/13 10:35
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * @Description:监听db:8
     * @author HeShengjin 2356899074@qq.com
     * @date 2023/1/13 10:39
     */
    @Override
    protected void doRegister(RedisMessageListenerContainer listenerContainer) {
        //database: 8
        listenerContainer.addMessageListener(this, new PatternTopic("__keyevent@8__:expired"));
    }

    /**
     * 过期消息
     *
     * @param message key
     * @param pattern 消息事件
     * @return void
     * @author lei
     * @date 2022-09-27 10:17:54
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        if (expiredKey.contains("TIME_OUT_KEY")) { // 判断是否是想要监听的过期key
            log.info("redis TIME_OUT_KEY过期：{}", expiredKey);
            //pattern:__keyevent@*__:expired
            log.info("redis pattern:{}", new String(pattern, StandardCharsets.UTF_8));
            // TODO 业务逻辑
        }

    }
}

